package com.wcar.vipmanagement.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcar.common.entity.CarStore;
import com.wcar.common.entity.StoreUser;
import com.wcar.common.entity.User;
import com.wcar.common.util.WebUtil;
import com.wcar.common.vo.Result;
import com.wcar.vipmanagement.dao.CarStoreMapper;
import com.wcar.vipmanagement.dao.StoreUserDao;
import com.wcar.vipmanagement.service.CarStoreService;
import com.wcar.vipmanagement.vo.CarStoreVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author 21147
* @description 针对表【tb_car_store】的数据库操作Service实现
* @createDate 2024-05-24 10:02:19
*/
@Service
public class CarStoreServiceImpl implements CarStoreService {
    @Resource
    private CarStoreMapper carStoreMapper;
    @Autowired
    private StoreUserDao storeUserDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result<Page<CarStore>> getCarList(CarStoreVo carStoreVo) {
        System.out.println(carStoreVo);
        //获取token
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        QueryWrapper<StoreUser> wrapper = new QueryWrapper<>();
        if(user.getUserId()!=1){
            wrapper.eq("user_id",user.getUserId());
        }
        List<StoreUser> storeUsers = storeUserDao.selectList(wrapper);
        ArrayList<Integer> userIds = new ArrayList<>();
        for (StoreUser storeUser : storeUsers) {
            userIds.add(storeUser.getStoreId());
        }
        IPage<CarStore> page = new Page<>(carStoreVo.getCurrentPage(),carStoreVo.getPageSize());
        QueryWrapper<CarStore> query = new QueryWrapper<>();
        if(carStoreVo.getCarNo()!=null&&carStoreVo.getCarNo()!=""){
            query.like("tcs.car_no",carStoreVo.getCarNo());
        }
        if(userIds.size()==0){
            return new Result<>(201,"获取车辆信息成功",null);
        }
        query.in("tcs.store_id",userIds);
        Page<CarStore> list = carStoreMapper.getPage(page,query);
        return new Result<>(200,"获取车辆信息成功",list);
    }

    @Override
    public Result<Integer> deleteCarStore(String carNo) {
        QueryWrapper<CarStore> wrapper=new QueryWrapper<>();
        wrapper.eq("car_no",carNo);
        carStoreMapper.delete(wrapper);
        return new Result<>(200,"",null);
    }
}




